﻿using CPPEI.Coolzon.Event.Core;
using CPPEI.Coolzon.Event.NCL;
using CPPEI.Coolzon.Metadata;
using CPPEI.Coolzon.UI;
using CPPEI.Coolzon.UI.Data;
using CPPEI.Coolzon.UI.Event;
using CPPEI.Coolzon.UI.Script;
using CPPEI.Coolzon.UI.Views;
using CPPEI.Coolzon.UI.Views.Events;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace CPPEI.Coolzon.Theme.Default.MainViewControl
{
    /// <summary>
    /// JSControlView.xaml 的交互逻辑
    /// </summary>
    public partial class JSControlView : UserControl
    {
        private DispatcherTimer dispatcherTime;
        private string CurrentSceneName;

        /// <summary>
        /// 目前弹出打开的场景列表
        /// </summary>
        private List<string> _popedSceneList;

        public JSControlView()
        {
            InitializeComponent();

            _popedSceneList = new List<string>();
        }

        /// <summary>
        /// 设置当前场景自定义事件按钮
        /// </summary>
        [Common.Subscribe]
        public void OnShowJSControl(ShowRecordEvent @event)
        {
            CPPEI.Coolzon.UI.Views.RenderView renderView = (CPPEI.Coolzon.UI.Views.RenderView)UI.UIContext.Current.RenderView;
            if (this.Visibility == System.Windows.Visibility.Visible)
            {
                this.Visibility = System.Windows.Visibility.Hidden;
                renderView.Visibility = System.Windows.Visibility.Visible;
                renderView.ValidateCurrentPartVisibleRange();
            }
            else
            {
                this.Visibility = System.Windows.Visibility.Visible;
                renderView.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private bool SetAction(List<CustomAction> actionList)
        {
            bool isVisible = false;
            if (actionList != null && actionList.Any())
            {
                actionList.ForEach((action) =>
                {
                    SetScriptButton(action);
                    isVisible = true;
                    //if (action.Steps != null && action.Steps.Any())
                    //{
                    //    action.Steps.ForEach((Step) =>
                    //    {
                    //    });
                    //}
                });
            }

            return isVisible;
        }

        [Common.Subscribe]
        public void OnOpened(CoreOpenSceneCompletedEvent @event)
        {
            Metadata.Scene openedSceneMetadata = Metadata.SolutionUtil.GetScene(UI.UIContext.Current.Solution, @event.SceneName);
            if (openedSceneMetadata != null)
            {
                if (CZEnvironment.IsShowActionPanelWhenOpenScene())
                {
                    this.Visibility = System.Windows.Visibility.Visible;

                    spRecord.Children.Clear();
                    CPPEI.Coolzon.UI.Views.RenderView renderView = (CPPEI.Coolzon.UI.Views.RenderView)UI.UIContext.Current.RenderView;
                    renderView.Visibility = System.Windows.Visibility.Hidden;

                    string actionFile = CZEnvironment.GetCustomActionFilePath(UIContext.Current.UserIdentity,
                        UIContext.Current.SolutionName, openedSceneMetadata.Name);
                    CPPEI.Coolzon.Metadata.ParserV1.SolutionXmlParser xmlParse = new Metadata.ParserV1.SolutionXmlParser();
                    List<CustomAction> customActionList = xmlParse.GetCustomActionList(actionFile);

                    SetAction(openedSceneMetadata.ShorcutActions);
                    SetAction(openedSceneMetadata.CustomActions);
                    SetAction(customActionList);
                }
                else
                {
                    this.Visibility = Visibility.Collapsed;
                }

                if (openedSceneMetadata.IsHorizontalLoopRender)
                {
                    leftLoop.Visibility = Visibility.Visible;
                    rightLoop.Visibility = Visibility.Visible;
                }
                else
                {
                    leftLoop.Visibility = Visibility.Hidden;
                    rightLoop.Visibility = Visibility.Hidden;
                }
                CurrentSceneName = @event.SceneName;

                if (@event.SwitchMode == SwitchMode.Pop)
                {
                    _popedSceneList.Add(@event.SceneName);
                    _ctlBtnClose.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    _popedSceneList.Clear();
                    _ctlBtnClose.Visibility = System.Windows.Visibility.Hidden;
                }
            }
            else
            {
                Common.Logger.ErrorToTag("UI", "快捷按钮面板,场景打开时，在方案中未发现场景:{0}", @event.SceneName);
            }
        }

        private void SetScriptButton(CustomAction action)
        {
            Button btn = new Button();
            btn.Width = 200;
            btn.Height = 60;
            btn.Margin = new Thickness(5);
            btn.Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF));
            //btn.Opacity = 0.6;
            btn.Content = action.Caption;
            btn.Tag = action;
            btn.Click += btn_Click;
            spRecord.Children.Add(btn);
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            CustomAction action = btn.Tag as CustomAction;
            for (int index = 0; index < action.Steps.Count; index++)
            {
                Common.EventBus.Instance.Publish(new ExecuteJSEvent(action.Caption, action.Steps[index].ScriptCode));
            }
        }

        private void btnRecord_Click(object sender, RoutedEventArgs e)
        {
            CPPEI.Coolzon.UI.Views.RenderView renderView = (CPPEI.Coolzon.UI.Views.RenderView)UI.UIContext.Current.RenderView;
            TranscribeWindow transcribeWindow = new TranscribeWindow(renderView.CurrentScene);
            transcribeWindow.Show();
        }

        private void _ctlBtnClose_Click_1(object sender, RoutedEventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Hidden;
        }

       
        [Common.Subscribe]
        public void OnHidden(CoreCloseSceneCompletedEvent @event)
        {
            if (@event.SwitchMode == SwitchMode.Pop)
            {
                // 移除场景
                for (int index = 0; index < _popedSceneList.Count; index++)
                {
                    if (_popedSceneList[index] == @event.SceneName)
                    {
                        _popedSceneList.RemoveAt(index);
                    }
                }

                if (_popedSceneList.Count > 0)
                {
                    _ctlBtnClose.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    // 没有场景不显示关闭按钮
                    _ctlBtnClose.Visibility = System.Windows.Visibility.Hidden;
                }

                //UI.ScenePart scenePart = ((UIContext.Current.RenderView as UI.Views.RenderView).GetCurrentPart() as ScenePart);
                //if (scenePart != null)
                //{
                //    if (scenePart.SceneMatadata.IsHorizontalLoopRender)
                //    {
                //        leftLoop.Visibility = Visibility.Visible;
                //        rightLoop.Visibility = Visibility.Visible;
                //    }
                //    else
                //    {
                //        leftLoop.Visibility = Visibility.Hidden;
                //        rightLoop.Visibility = Visibility.Hidden;
                //    }

                //    CurrentSceneName = scenePart.SceneMatadata.Name;
                //}
            }
        }

        private void leftLoop_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            leftLoop.Opacity = 100;
        }

        private void rightLoop_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            rightLoop.Opacity = 100;
        }

        private void leftLoop_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            leftLoop.Opacity = 0.2;
        }

        private void rightLoop_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            rightLoop.Opacity = 0.2;
        }
        private void leftLoop_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Common.EventBus.Instance.Publish(new UI.Event.LoopSceneEvent(0, CurrentSceneName, 200));
            Debug.Write("Loop到上一个场景");

            InitDispatcherTime();
            StartDispatcherTime(0);
        }
        private void rightLoop_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Common.EventBus.Instance.Publish(new UI.Event.LoopSceneEvent(2, CurrentSceneName, 200));
            Debug.Write("Loop到下一个场景");

            InitDispatcherTime();
            StartDispatcherTime(2);
        }

        private void leftLoop_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            StopDispatcherTime();
        }

        private void rightLoop_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            StopDispatcherTime();
        }
        private void InitDispatcherTime()
        {
            if (dispatcherTime == null)
            {
                dispatcherTime = new DispatcherTimer();
                dispatcherTime.Tick += dispatcherTime_Tick;
                dispatcherTime.IsEnabled = false;
                dispatcherTime.Interval = TimeSpan.FromMilliseconds(500);
            }
        }

        void dispatcherTime_Tick(object sender, EventArgs e)
        {
            if (System.Windows.Input.Mouse.LeftButton == MouseButtonState.Pressed
                || System.Windows.Input.Mouse.RightButton == MouseButtonState.Pressed)
            {
                Common.EventBus.Instance.Publish(new UI.Event.LoopSceneEvent(Convert.ToInt32(dispatcherTime.Tag), CurrentSceneName, 200));
            }
        }

        private void StopDispatcherTime()
        {
            if (dispatcherTime != null && dispatcherTime.IsEnabled)
            {
                dispatcherTime.Stop();
                dispatcherTime.IsEnabled = false;
            }
        }

        private void StartDispatcherTime(int direction)
        {
            if (!dispatcherTime.IsEnabled)
            {
                dispatcherTime.Tag = direction;
                dispatcherTime.IsEnabled = true;
                dispatcherTime.Start();
            }
        }

        private void _ctlBtnClose_Click(object sender, RoutedEventArgs e)
        {
            if (_popedSceneList.Count > 0)
            {
                string closingScene = _popedSceneList[_popedSceneList.Count - 1];
                if (!string.IsNullOrEmpty(closingScene))
                {
                    CoreEventBus.Publish(new CoreCloseSceneEvent(SwitchMode.Pop,"",closingScene));
                }
            }
        }


        #region 触摸相关事件
        private void rightLoop_TouchDown(object sender, TouchEventArgs e)
        {
            Common.EventBus.Instance.Publish(new UI.Event.LoopSceneEvent(2, CurrentSceneName, 200));
            Debug.Write("Loop到下一个场景");

            InitDispatcherTime();
            StartDispatcherTime(2);
        }

        private void rightLoop_TouchUp(object sender, TouchEventArgs e)
        {
            StopDispatcherTime();
        }

        private void rightLoop_TouchEnter(object sender, TouchEventArgs e)
        {
            rightLoop.Opacity = 100;
        }

        private void rightLoop_TouchLeave(object sender, TouchEventArgs e)
        {
            rightLoop.Opacity = 0.2;
        }

        private void leftLoop_TouchDown(object sender, TouchEventArgs e)
        {
            Common.EventBus.Instance.Publish(new UI.Event.LoopSceneEvent(0, CurrentSceneName, 200));
            Debug.Write("Loop到上一个场景");

            InitDispatcherTime();
            StartDispatcherTime(0);
        }

        private void leftLoop_TouchUp(object sender, TouchEventArgs e)
        {
            StopDispatcherTime();
        }

        private void leftLoop_TouchEnter(object sender, TouchEventArgs e)
        {
            leftLoop.Opacity = 100;
        }

        private void leftLoop_TouchLeave(object sender, TouchEventArgs e)
        {
            leftLoop.Opacity = 0.2;
        }
        #endregion

    }
}
